package marksys.free.com.marksys.ui.face.facebykomlin;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;

import java.io.IOException;
import java.util.List;

import marksys.free.com.marksys.ui.face.facebykomlin.callback.AutoFocusCallback;

public class CameraInterface {
    private static final String TAG = "CameraInterface";
    private Camera mCamera;
    private Camera.Parameters mParams;

    private boolean isPreviewing = false;
    private float mPreviwRate = -1f;
    private static CameraInterface mCameraInterface;

    public interface CamOpenOverCallback {
        void cameraHasOpened();
    }

    AutoFocusCallback autoFocusCallback;
    Handler handler;
    public static int MSG_AUTOFUCS_0 = 0;

    private CameraInterface() {

    }

    public static synchronized CameraInterface getInstance() {
        if (mCameraInterface == null) {
            mCameraInterface = new CameraInterface();
        }
        return mCameraInterface;
    }

    /**
     * 打开Camera
     *
     * @param callback
     */
    public void doOpenCamera(Context activity, CamOpenOverCallback callback) {
        Log.i(TAG, "Camera open....");
        if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) activity, new String[]{android.Manifest.permission.CAMERA}, 1);
            Log.e(TAG, "Camera open requestPermissions");
        } else {
            mCamera = Camera.open();
            Log.i(TAG, "Camera open over....");
            callback.cameraHasOpened();
        }

    }

    /**
     * 开启预览
     *
     * @param holder
     */
    @SuppressLint("HandlerLeak")
    public void doStartPreview(Context context, SurfaceHolder holder, CameraSurfaceView surfaceView) {
        Log.i(TAG, "doStartPreview...");
        if (isPreviewing) {
            mCamera.stopPreview();
            return;
        }
        if (mCamera != null) {

            mParams = mCamera.getParameters();


            mParams.setPictureFormat(PixelFormat.JPEG);//设置拍照后存储的图片格式

            List<String> focusModes = mParams.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                // Autofocus mode is supported
                mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            }


            Resources resources = context.getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();
            float density = dm.density;
            int screenWidth = dm.widthPixels;
            int screenHeight = dm.heightPixels;


            Camera.Size preSize = CamParaUtil.getCloselyPreSize(true, screenWidth, screenHeight, mParams.getSupportedPreviewSizes());
            mParams.setPreviewSize(preSize.width, preSize.height);


            // 横竖屏镜头自动调整
            if (context.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                mParams.set("orientation", "portrait"); //
                mParams.set("rotation", 90); // 镜头角度转90度（默认摄像头是横拍）
                mCamera.setDisplayOrientation(90); // 在2.2以上可以使用
            } else// 如果是横屏
            {
                mParams.set("orientation", "landscape"); //
                mCamera.setDisplayOrientation(0); // 在2.2以上可以使用
            }
            mCamera.setParameters(mParams);  //参数设置完毕

            if (mParams.getMaxNumDetectedFaces() > 0) {
                mCamera.setFaceDetectionListener(surfaceView);//数据回调
            }
            try {
                mCamera.setPreviewDisplay(holder);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // mCamera.setPreviewCallback(surfaceView);
            mCamera.startPreview();//开启预览
            if (mParams.getMaxNumDetectedFaces() > 0) {
                mCamera.startFaceDetection();
            }

            isPreviewing = true;

/*
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Log.e("自动对焦", "" + msg.what);
                    switch (msg.what) {
                        case 0:
                            mCamera.autoFocus(autoFocusCallback);
                            break;
                    }
                }
            };

            autoFocusCallback = new AutoFocusCallback();
            autoFocusCallback.setHandler(handler, MSG_AUTOFUCS_0);
            mCamera.autoFocus(autoFocusCallback);*/
            ;
        }
    }


    /**
     * 停止预览，释放Camera
     */
    public void doStopCamera() {
        if (null != mCamera) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            isPreviewing = false;
            mCamera.release();
            mCamera = null;
        }
    }

}
